package com.netstar.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.netstar.R;

public class DownloadUtil extends Thread {

	private static final String TAG = "DownloadUtil";

	private Context mContext;
	private String mDownloadUrl; // 文件下载url，已做非空检查
	private String mFileName;

	private NotificationManager mNotifManager;
	private Notification mDownNotification;
	private RemoteViews mContentView; // 下载进度View
	private PendingIntent mDownPendingIntent;

	public DownloadUtil(Context context, String downloadUrl, String fileName) {
		mContext = context;
		mDownloadUrl = downloadUrl;
		mFileName = fileName;
		mNotifManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
	}

	@Override
	public void run() {
		try {
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
				// SD卡准备好
				File folder = new File(FileUtil.FILE_PATH);
				if (!folder.exists()) {
					// 创建存放目录
					folder.mkdir();
				}
				mDownNotification = new Notification(
						android.R.drawable.stat_sys_download, "下载文件", System.currentTimeMillis());
				mDownNotification.flags = Notification.FLAG_ONGOING_EVENT;
				mDownNotification.flags = Notification.FLAG_AUTO_CANCEL;
				mContentView = new RemoteViews(mContext.getPackageName(), R.layout.notifycation_layout);
				mContentView.setImageViewResource(R.id.downLoadIcon, android.R.drawable.stat_sys_download);
				mDownPendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(), 0);
				boolean isDownSuccess = downloadFile(mDownloadUrl, FileUtil.FILE_PATH, mFileName);
			} else {
			}
		} catch (Exception e) {
			Log.e(TAG, "AppFileDownUtils catch Exception:", e);
		}
	}

	/**
	 * 
	 * Desc:文件下载
	 * 
	 * @param downloadUrl
	 *            下载URL
	 * @param saveFilePath
	 *            保存文件路径
	 * @return ture:下载成功 false:下载失败
	 */
	public boolean downloadFile(String downloadUrl, String path, String fileName) {

		int fileSize = -1;
		int downFileSize = 0;
		boolean result = false;
		int progress = 0;
		try {

			if (!path.endsWith("/")) {
				path += "/";
			}
			String filePath = path + fileName;
			EvtLog.d("test", "当前文件路径为:   " + filePath);
			if (FileUtil.isFileExist(filePath)) {
				FileUtil.deleteDir(filePath);
			}

			URL url = new URL(downloadUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			if (null == conn) {
				return false;
			}
			// 读取超时时间 毫秒级
			conn.setReadTimeout(10000);
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			conn.connect();
			if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
				InputStream is = conn.getInputStream();
				fileSize = conn.getContentLength();
				FileOutputStream fos = new FileOutputStream(filePath);
				byte[] buffer = new byte[1024];
				int bufferLength = 0;
				int tempProgress = -1;
				while ((bufferLength = is.read(buffer)) != -1) {
					downFileSize = downFileSize + bufferLength;
					// 下载进度
					progress = (int) (downFileSize * 100.0 / fileSize);
					fos.write(buffer, 0, bufferLength);
					synchronized (this) {
						if (downFileSize == fileSize) {
							// 下载完成
							mNotifManager.cancel(R.id.downLoadIcon);
						} else if (tempProgress != progress) {
							// 下载进度发生改变，则发送Message
							mContentView.setTextViewText(R.id.progressPercent, progress + "%");
							mContentView.setProgressBar(R.id.downLoadProgress, 100, progress, false);
							mDownNotification.contentView = mContentView;
							mDownNotification.contentIntent = mDownPendingIntent;
							mNotifManager.notify(R.id.downLoadIcon, mDownNotification);
							tempProgress = progress;
						}
					}
				}
				fos.flush();
				fos.close();
				is.close();
				result = true;
			} else {
				result = false;
			}
		} catch (Exception e) {
			result = false;
			Log.e(TAG, "downloadFile catch Exception:", e);
		}
		return result;
	}
}
